//
//  MyFavorite.m
//  Car
//
//  Created by 何晓文 on 15/10/5.
//  Copyright © 2015年 朱鸿儒. All rights reserved.
//

#import "MyFavorite.h"
#import "FMDB.h"


@implementation MyFavorite
static MyFavorite *myFavorite;
static FMDatabase *_myDB;

+ (MyFavorite *)shareFavorite {

	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		if (myFavorite == nil) {
			myFavorite = [[MyFavorite alloc] init];
		}
	});
	return myFavorite;
}
- (NSString *)getSqlitePathWithUser:(NSString *)user {

	//获取document路径
	NSString *docPath = [NSSearchPathForDirectoriesInDomains(9, 9, 1) lastObject];
	//拼接文件路径
	NSString *filePath = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@favoriteBeauty.sqlite", user]];
	NSLog(@"%@", filePath);
	return filePath;
}
/**
 *添加收藏
 */
- (void)addBeautyModel:(BeautyModel *)BeautyModel WithUser:(NSString *)user {

	//创建数据库文件
	_myDB = [FMDatabase databaseWithPath:[self getSqlitePathWithUser:user]];
	//链接数据库
	[_myDB open];
	NSString *slq = [NSString stringWithFormat:@"create table if not exists favoriteBeauty (id integer primary key,title text not null,imageUrl text,topicid text UNIQUE);"];
	//创建表
	[_myDB executeUpdate:slq];

	//插入数据
	BOOL done = [_myDB executeUpdateWithFormat:@"insert into favoriteBeauty (title,imageUrl, topicid) values (%@,%@,%@);",BeautyModel.title, BeautyModel.smallpic,BeautyModel.topicid];
	if (done) {
		[ProgressHUD showSuccess:@"收藏成功"];
	}else {
		[ProgressHUD showError:@"重复收藏"];
	}
	
}
- (void)deleteBeautyByTopicid:(NSString *)topicid WithUser:(NSString *)user {
	_myDB = [FMDatabase databaseWithPath:[self getSqlitePathWithUser:user]];
	[_myDB open];
	NSString *slq = [NSString stringWithFormat:@"delete from favoriteBeauty where topicid = %@", topicid];
	BOOL result = [_myDB executeUpdate:slq];
	if (result) {
		[ProgressHUD showSuccess:@"删除成功"];
	}else {
		[ProgressHUD showError:@"删除失败"];
	}

}
/**
 *  遍历数据
 */
- (NSMutableArray *)extractDataWithUser:(NSString *)user {
	NSMutableArray *array = [NSMutableArray array];
	
	_myDB = [FMDatabase databaseWithPath:[self getSqlitePathWithUser:user]];
	[_myDB open];
	
	//查询所有音乐收藏数据
	NSString *sql = [NSString stringWithFormat:@"select * from favoriteBeauty"];
	FMResultSet *set = [_myDB executeQuery:sql];
	while (set.next) {
		//将数据库中的blob转化为data
		
		//初始化model接收
		BeautyModel *model = [[BeautyModel alloc] init];
		model.title = [set objectForColumnName:@"title"];
		model.smallpic = [set objectForColumnName:@"imageUrl"];
		model.topicid = [set objectForColumnName:@"topicid"];
		
		NSLog(@"%@",model.title);
		[array addObject:model];
	}

	return array;

}

@end
